package utils

import (
	"log"
	"os"
	"strconv"
	"syscall"
	"time"
)

func ScheduleToWrite(filename string, prefix string) error {
	file, err := os.OpenFile(filename, os.O_RDWR|os.O_RDWR, 0x777)
	if err != nil {
		return err
	}

	n := 0

	tk := time.Tick(time.Second)

	for {
		if n > 2000 {
			break
		}
		<-tk
		n++
		_, _ = file.WriteString(prefix + strconv.Itoa(n) + "\n")
	}

	return nil
}

func ScheduleToWriteWithFLock(filename, prefix string) error {
	f, err := os.Create("/Users/xianmingliu/xsomnus/go/src/go-arch/linux/filelocks/LOCK")
	if err != nil {
		log.Fatalf("failed to create filelock, %+v\n", err)
	}

	defer f.Close()

	if err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX); err != nil {
		log.Fatalf("add share lock in no block failed, %+v\n", err)
	}

	return ScheduleToWrite(filename, prefix)
}
